class CharacterTrait < ActiveRecord::Base
  belongs_to    :trait
  belongs_to    :character
  
  def CharacterTrait.random_traits(character, education_preference = nil, max_body = 3, max_soul = 3, max_virtues = 3, max_sins = 3)
    CharacterTrait.assign_random_traits character, Trait.find_all_body, max_body
    CharacterTrait.assign_random_traits character, Trait.find_all_soul, max_soul
    CharacterTrait.assign_random_traits character, Trait.find_all_virtues, max_virtues
    CharacterTrait.assign_random_traits character, Trait.find_all_sins, max_sins
    if education_preference.nil?
      x = rand(character.male? ? 2 : 1)
      if x == 0
        education_preference = "Court"
      elsif x == 1
        education_preference = "Ecclesiastical" 
      elsif x == 2
        education_preference = "Martial"
      end
    end
    if education_preference == "Ecclesiastical"
      Title.make_priest character
    else
      Title.make_lord character
    end
    
    if character.adult?
      if education_preference == "Court"
        CharacterTrait.assign_random_traits character, Trait.find_all_court_education, 1, 1
      elsif education_preference == "Ecclesiastical"
        CharacterTrait.assign_random_traits character, Trait.find_all_ecclesiastical_education, 1, 1
      elsif education_preference == "Martial"
        CharacterTrait.assign_random_traits character, Trait.find_all_military_education, 1, 1
      end
    elsif character.student?
      trait = Trait.find_by_name("Initial #{education_preference} Education")
      if trait
        ct = CharacterTrait.new
        ct.trait_id = trait.id
        ct.character_id = character.id
        ct.save
      end
    end
  end
  
  protected
    def CharacterTrait.assign_random_traits(character, traits, max, min = 0)
      if traits && traits.size > 0
        x = 0
        total = rand(max - min) + min
        while x < total do
          trait = traits[rand(traits.size)]    
          ct = CharacterTrait.new
          ct.trait_id = trait.id
          ct.character_id = character.id
          ct.save
        end
      end
    end
  
end
